package xyz.yeidi.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import xyz.yeidi.pojo.User;
import xyz.yeidi.service.api.UserService;
import xyz.yeidi.utils.ServiceFactory;
import xyz.yeidi.utils.EncryptionUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author JIP
 * @Date 2021-07-28 15:37
 * @Version 1.0
 * @Describe :  登录页面
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        PrintWriter out = response.getWriter();
        ObjectMapper om = new ObjectMapper();
        UserService userService = ServiceFactory.getUserService();
        //需要先把用户密码加密成服务器中的模样
        password = EncryptionUtils.encryption(password);
        User user = userService.getUserByNameAndPassword(username, password);
        if(user!=null){
            out.print(om.writeValueAsString(user));
        }else{
            out.print(om.writeValueAsString("no_user"));
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
